<!-- eslint-disable vue/valid-template-root -->
<template>
    <div id="main">
        <!-- 面包屑 -->
        <go-bread :beacklist="beacklist"></go-bread>
        <div class="wrapper">
            <!-- 头部搜索框 -->
            <div class="titleBox">
                <el-row>
                    <el-col :span="12">
                        <!-- <div class="searchBox"> -->
                        <el-input placeholder="请输入内容" v-model="searchValue" class="input-with-select" @input="ySearch"
                            clearable>
                            <el-button slot="append" icon="el-icon-search" @click="searchBtn"></el-button>
                        </el-input>
                        <!-- </div> -->
                    </el-col>
                    <el-col :span="6" :offset="1">
                        <el-button type="primary" @click="addUserBtn">添加用户</el-button>
                    </el-col>
                </el-row>
            </div>
            <!-- table表格 -->
            <div class="tableBox">
                <el-table :data="userlist" border stripe style="width: 100%">
                    <el-table-column label="#" type="index" width="50">
                    </el-table-column>
                    <el-table-column prop="username" label="姓名">
                    </el-table-column>
                    <el-table-column prop="email" label="邮箱">
                    </el-table-column>
                    <el-table-column prop="mobile" label="电话">
                    </el-table-column>
                    <el-table-column prop="role_name" label="角色">
                    </el-table-column>
                    <el-table-column prop="name" label="状态">
                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.mg_state"
                                @change="statusFun(scope.row.id, scope.row.mg_state)" active-color="#409EFF"
                                inactive-color="#dcdfe6">
                            </el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="操作">
                        <template slot-scope="scope">
                            <el-button type="primary" size="mini" icon="el-icon-edit" @click="amendBtn(scope.row)"
                                circle></el-button>
                            <el-button type="warning" size="mini" icon="el-icon-setting" circle
                                @click="allotRoleFun(scope.row)"></el-button>
                            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deteleUser(scope.row.id)"
                                circle></el-button>

                        </template>
                    </el-table-column>

                </el-table>
                <!-- 分页器 -->
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :page-sizes="[5, 10, 15, 20]" :page-size="this.limit"
                    layout="total, sizes, prev, pager, next, jumper" :total="this.total">
                </el-pagination>
            </div>
            <!-- 添加用户弹框 -->
            <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
                <el-form :model="userform" :rules="rules" ref="userform">
                    <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
                        <el-input v-model="userform.username" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password" :label-width="formLabelWidth">
                        <el-input v-model="userform.password" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
                        <el-input v-model="userform.email" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="手机" prop="mobile" :label-width="formLabelWidth">
                        <el-input v-model="userform.mobile" autocomplete="off"></el-input>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addUser('userform')">确 定</el-button>
                </div>
            </el-dialog>
            <!-- 修改用户弹框 -->
            <el-dialog title="修改用户" :visible.sync="dialogflag">
                <el-form :model="amendform" :rules="rules2" ref="amendform">
                    <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
                        <el-input v-model="amendform.username" autocomplete="off" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
                        <el-input v-model="amendform.email" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="手机" prop="mobile" :label-width="formLabelWidth">
                        <el-input v-model="amendform.mobile" autocomplete="off"></el-input>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogflag = false">取 消</el-button>
                    <el-button type="primary" @click="amendUser">确 定</el-button>
                </div>
            </el-dialog>
            <!-- 分配角色弹框 -->
            <el-dialog title="分配角色" :visible.sync="allotRoleDialogflag">
                <el-form :model="setRoleList" ref="setRoleList">
                    <el-form-item label="用户名" :label-width="formLabelWidth">
                        </el-input><span>{{ this.setRoleList.username }}</span>
                    </el-form-item>
                    <el-form-item label="当前角色" :label-width="formLabelWidth">
                        </el-input><span>{{ this.setRoleList.role_name }}</span>
                    </el-form-item>
                    <el-form-item label="分配新角色" :label-width="formLabelWidth">
                        <el-select v-model="roleSelectVal" placeholder="请选择">
                            <el-option :label="i.roleName" :value="i.id" v-for="i in this.rolesList" :key="i.id">
                            </el-option>
                        </el-select>
                    </el-form-item>


                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="allotRoleDialogflag = false">取 消</el-button>
                    <el-button type="primary" @click="allotRoleFn">确 定</el-button>
                </div>
            </el-dialog>

        </div>
    </div>
</template>
<script>
import { GetUsers, SetStatus, addUserPort, deleteUserPort, amendUserPort, getRolesPort, setRolesPort, getIdUser } from '@/api/user'
import { mapGetters } from 'vuex';
import _ from 'lodash'
export default {
    data() {
        var checkphone = (rule, value, callback) => {
            // let phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/;
            if (value === "") {
                // callback(new Error("请输入电话"));
            } else if (!this.isCellPhone(value)) {
                // 引入methods中封装的检查手机格式的方法
                callback(new Error("请输入正确的电话!"));
            } else {
                callback();
            }
        };
        return {
            searchValue: '',
            limit: 5,
            page: 1,
            total: 0,
            userlist: [],
            statusflag: null,
            dialogFormVisible: false,
            userform: {
                username: '',
                password: '',
                mobile: '',
                email: ''
            },
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 8, message: '长度在 6 到 8 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                ],
                mobile: [
                    { required: true, message: '请输入电话', trigger: 'blur' },
                    { validator: checkphone, trigger: ['blur', 'change'] },
                ]
            },
            rules2: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                ],
                email: [
                    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                ],
                mobile: [
                    { required: true, validator: checkphone, trigger: ['blur', 'change'] },
                ]
            },
            formLabelWidth: '100px',
            dialogflag: false,
            amendform: {
                username: '',
                email: '',
                mobile: '',
            },
            allotRoleDialogflag: false,
            rolesList: [],
            setRoleList: {},
            roleSelectVal: '',
            setroleId: '',
            getIdd: '', //根据id查询数据
        }
    },
    watch: {
        dialogFormVisible(v) {
            // console.log(v);
            if (!v) {
                this.$refs["userform"].resetFields();
            }
        }
    },
    components: {
        // eslint-disable-next-line vue/no-unused-components
       
    },
    computed: {
        ...mapGetters(['beacklist'])
    },
    async created() {
        let res = await GetUsers(this.searchValue, this.limit, this.page)
        if (res.meta.status == 200) {
            this.userlist = res.data.users
            this.total = res.data.total
        }
    },
    mounted() {

    },
    methods: {
        //防抖
        // ySearch:_.debounce(function(){
        //     this.searchBtn()
        // },5000),
        //节流
        ySearch: _.throttle(function () {
            this.searchBtn()
        }, 5000),
        isCellPhone(val) {
            if (!/^1(3|4|5|6|7|8)\d{9}$/.test(val)) {
                return false;
            } else {
                return true;
            }
        },
        async searchBtn() { //搜索
            let res = await GetUsers(this.searchValue, this.limit, this.page)
            if (res.meta.status == 200) {
                let data = res.data
                this.userlist = data.users
                this.total = data.total
            }
        },
        async statusFun(id, flag) { //状态
            // console.log(flag);
            this.statusflag = flag
            let res = await SetStatus(id, flag)
            if (res.meta.status == 200) {
                this.$message({
                    showClose: true,
                    message: res.meta.msg,
                    type: 'success'
                })
                this.searchBtn()
                // console.log('sssss');
            }
        },
        handleSizeChange(val) {
            // console.log(`每页 ${val} 条`);
            this.limit = val
            this.searchBtn()
        },
        handleCurrentChange(val) {
            this.page = val
            // console.log(`当前页: ${val}`);
            this.searchBtn()
        },
        addUserBtn() { //清空
            this.userform.username = ''
            this.userform.password = ''
            this.userform.mobile = ''
            this.userform.email = ''
            this.dialogFormVisible = true
        },
        addUser(formName) { //添加用户
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    this.dialogFormVisible = false
                    let res = await addUserPort(this.userform)
                    if (res.meta.status) {
                        this.$message({
                            showClose: true,
                            message: res.meta.msg,
                            type: 'success'
                        })
                        this.searchBtn()
                    }
                }
            })

        },
        async deteleUser(id) { //删除用户
            if (this.userlist.length <= 1) {
                this.page = this.page - 1
            }
            // console.log(this.userlist.length);
            let res = await deleteUserPort(id)
            if (res.meta.status == 200) {
                this.$message({
                    showClose: true,
                    message: res.meta.msg,
                    type: 'success'
                })
                this.searchBtn()
            } else {
                this.$message({
                    showClose: true,
                    message: '删除失败',
                    type: 'error'
                })
                this.searchBtn()
            }
        },
        async amendUser() { //修改
            this.dialogflag = false
            let { id, mobile, email } = this.amendform
            let res = await amendUserPort(id, { mobile, email })
            if (res.meta.status == 200) {
                this.$message({
                    showClose: true,
                    message: '修改成功',
                    type: 'success'
                })
                this.searchBtn()
            } else {
                this.$message({
                    showClose: true,
                    message: '修改失败',
                    type: 'error'
                })
                this.searchBtn()
            }
        },
        async amendBtn(data) {
            let res = await getIdUser(data.id)
            // console.log('-----', res);

            this.getIdd = data.id
            this.amendform = res.data
            this.dialogflag = true
        },
        async allotRoleFun(data) {//分配角色按钮
            this.allotRoleDialogflag = true
            this.setRoleList = data
            this.setroleId = data.id
            let res = await getRolesPort()
            // console.log(res);
            if (res.meta.status == 200) {
                this.rolesList = res.data
            }

        },
        async allotRoleFn() {//分配角色确认按钮
            let res = await setRolesPort(this.setroleId, this.roleSelectVal)
            // console.log(res);
            if (res.meta.status == 200) {
                this.$message.success(res.meta.msg)
                this.allotRoleDialogflag = false
                this.roleSelectVal = ''
                this.searchBtn()
            } else {
                this.$message.success(res.meta.msg)
                this.allotRoleDialogflag = false
                this.roleSelectVal = ''
                this.searchBtn()
            }

        }
    }
}
</script>
<style scoped lang="scss">
#main {
    width: 100%;
    min-width: 1126px;
    height: 100%;
    background: #fff;
}

.wrapper {
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    padding: 20px;
}

.titleBox {
    width: 100%;

    height: 40px;
    // display: flex;

    .searchBox {
        width: 24.2%;
        box-sizing: border-box;
        padding: 0 10px 0 0;
        margin-right: 10px;
    }
}

.tableBox {
    width: 100%;
    margin-top: 15px;

    /deep/ .el-table th.el-table__cell>.cell {
        font-size: 14px;
        font-weight: bold;
    }

}

.el-pagination {
    margin-top: 15px;

}
</style>